package com.example.springboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.springboot.common.Constants;
import com.example.springboot.common.Page;
import com.example.springboot.common.Result;
import com.example.springboot.entity.CComment;
import com.example.springboot.entity.Creative;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.mapper.CCommentMapper;
import com.example.springboot.service.ICCommentService;
import com.example.springboot.service.ICreativeService;
import com.example.springboot.utils.TimeUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springboot.utils.SensitiveWordUtil;
import com.example.springboot.utils.TokenUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class CCommentServiceImpl extends ServiceImpl<CCommentMapper, CComment> implements ICCommentService {

    @Resource
    private CCommentMapper cCommentMapper;
    @Resource
    private ICCommentService commentService;
    @Resource
    private ICreativeService creativeService;

    @Override
    public List<CComment> getCommentsByCreative(Integer creativeId) {
        //查找该创意下所有已发布评论
        List<CComment> commentList = cCommentMapper.getCommentsByCreative(creativeId);
        for (CComment cComment : commentList){
            cComment.setMine(cComment.getUserId().equals(Objects.requireNonNull(TokenUtils.getCurrentUser()).getId()));
            cComment.setRelativeTime(TimeUtil.createRelative(cComment.getCreateTime()));
        }
        //查找所有父级评论
        List<CComment> originList = commentList.stream().filter(cComment -> cComment.getOriginId() == null).collect(Collectors.toList());
        //对每个父级评论设置子评论列表
        for (CComment origin : originList) {
            //回复评论列表
            List<CComment> childrenList = commentList.stream().filter(cComment -> origin.getId().equals(cComment.getOriginId())).collect(Collectors.toList());
            //对其中的评论设置父级评论的用户id和昵称
            childrenList.forEach(cComment -> {
                commentList.stream().filter(c1 -> c1.getId().equals(cComment.getPid())).findFirst().ifPresent((v -> {
                    cComment.setPUserId(v.getUserId());
                    cComment.setPNickname(v.getNickname());
                }));
            });
            origin.setChildren(childrenList);
        }
        return originList;
    }

    @Override
    public int getCount(Integer creativeId) {
        QueryWrapper<CComment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("creative_id",creativeId);
        return cCommentMapper.selectList(queryWrapper).size();
    }

    @Override   //插入评论
    public CComment insert(CComment cComment) throws IOException {
        //判断评论创意是否存在
        Creative creative;
        try {
            creative = creativeService.getById(cComment.getCreativeId());
        }catch (Exception e) {
            throw new ServiceException(Constants.CODE_500,"系统错误");
        }
        if (creative == null)
            throw new ServiceException(Constants.CODE_600,"创意不存在");
        else if (!creative.getStatement().equals("已发布"))
            throw new ServiceException(Constants.CODE_600,"创意不存在");
        cComment.setContent(SensitiveWordUtil.sensitiveHelper(cComment.getContent()));
        //判断父评论是否存在
        QueryWrapper<CComment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",cComment.getOriginId()).or().eq("id",cComment.getPid());
        List<CComment> back = cCommentMapper.selectList(queryWrapper);
        if (cComment.getPid() == null && cComment.getOriginId() == null)
            cCommentMapper.insert(cComment);
        else if (cComment.getOriginId().equals(cComment.getPid())) {
            if (back.size() == 0)
                return null;
            cCommentMapper.insert(cComment);
        }
        else {
            if (back.size() != 2)
                return null;
            cCommentMapper.insert(cComment);
        }
        return cComment;
    }

    @Override
    public boolean deleteOne(Integer id) {
        QueryWrapper<CComment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pid",id).or().eq("origin_id",id).or().eq("id",id);
        return commentService.remove(queryWrapper);
    }

    @Override
    public boolean removeByCreative(Integer creativeId) {
        QueryWrapper<CComment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("creative_id",creativeId);
        return commentService.remove(queryWrapper);
    }

    @Override   //管理员获取评论列表
    public Result adminGet(int PageNum, int PageSize, String content) {
        QueryWrapper<CComment> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("content","该评论包含敏感词汇，已被屏蔽。");
        queryWrapper.like("content",content);
        List<CComment> cCommentList = commentService.list(queryWrapper);
        cCommentList.sort(Comparator.comparing(CComment::getCreateTime).reversed());
        Page page = new Page();
        return Result.success(page.startPage(cCommentList,PageNum,PageSize));
    }

    @Override   //管理员处理违规评论
    public Result processComment(Integer id) {
        CComment find;
        try {
            find = commentService.getById(id);
        }catch (Exception e) {
            throw new ServiceException(Constants.CODE_500,"系统错误");
        }
        if (find == null)
            return Result.error(Constants.CODE_600,"该评论不存在");
        CComment cComment = new CComment();
        cComment.setId(id);
        cComment.setContent("该评论包含敏感词汇，已被屏蔽。");
        if (commentService.saveOrUpdate(cComment))
            return Result.success("处理成功");
        return Result.error(Constants.CODE_600,"处理失败");
    }


}
